﻿using LJX.SmartPark.Common.Config;
using LJX.SmartPark.Common.Const;
using LJX.SmartPark.EntityFramework;
using LJX.SmartPark.Service;
using LJX.SmartPark.Service.Repository;
using System.Reflection;
using Microsoft.EntityFrameworkCore;

namespace LJX.SmartPark.WebApi.Extensions
{
    public static class ServiceRegister
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceCollection"></param>
        /// <returns></returns>
        public static IServiceCollection ServicesRegister(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddHttpContextAccessor();

            MsSqlDbContextRegister(serviceCollection);

            serviceCollection.AddTransient(typeof(IRepository<>), typeof(Repository<>));

            Assembly assembly = Assembly.Load(AssemblyConst.SMARTPARKSERVER_SERVICE);
            var services = assembly.GetTypes().Where(c => c.IsAssignableTo(typeof(ITransientService))
            && !c.IsAbstract && !c.IsInterface);
            foreach (var service in services)
            {
                var iservice = service.GetInterfaces().FirstOrDefault(c => c.Name != nameof(ITransientService));
                if (iservice != null)
                {
                    serviceCollection.AddTransient(iservice, service);
                }
            }
            return serviceCollection;
        }

        /// <summary>
        /// 注入EFCore
        /// </summary>
        /// <param name="serviceCollection"></param>
        private static void MsSqlDbContextRegister(IServiceCollection serviceCollection)
        {
            serviceCollection.AddDbContext<StudentServerContext>(opt =>
            {
                string connectionString = AppSettings.AppConfigOwn.MSSql;
                opt.UseSqlServer(connectionString, c => c.MigrationsAssembly(AssemblyConst.MIGRAGTIONSASSEMBLY));
            });
        }
    }
}
